package com.changgou.order.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.order.service.OrderService;
import com.changgou.pay.feign.PayFeign;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Map;

/**
 * 接受支付下单后的队列信息
 * @author 戴金华
 * @date 2019-12-26 22:13
 */
@Component
@RabbitListener(queues = "queue.order")
public class OrderMessageListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayFeign payFeign;

    /**
     * 队列监听 取出队列中的订单信息
     * 判断用户是否支付成功 如果支付成功则修改订单状态
     *                  如果支付失败 则将库存回滚 同时向微信服务器发送请求 关闭该订单的微信支付
     * @param message
     * @throws Exception
     */
    @RabbitHandler
    public void getMessage(String message) throws Exception {
        Map<String, String> map = JSON.parseObject(message, Map.class);

        //返回状态码
        String return_code = map.get("return_code");

        //订单号(订单id)
        String out_trade_no = map.get("out_trade_no");

        String transaction_id = map.get("transaction_id");

        //如果状态码为success
        if ("SUCCESS".equals(return_code)) {
            //业务结果
            String result_code = map.get("result_code");
            if ("SUCCESS".equals(result_code)) {
                //如果交易成功 修改订单状态
                try {
                    orderService.updateStatus(out_trade_no,map.get("time_end"),transaction_id);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            } else {
                //如果交易失败 则库存回滚
                orderService.deleteOrder(out_trade_no);
                //关闭支付
                payFeign.closeOrder(out_trade_no);
            }

        }

    }

}

